package com.fafa.swing.base;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

/**
 * @author : fafa
 * @version V1.0
 * @Project: SwingTest
 * @Package com.fafa.swing
 * @Description: JTableRowDelDemo
 * @date Date : 2019年11月26日 21:43
 */
public class JTableRowDelDemo extends JFrame {

    private JPanel jPanel;
    private JTable jTable;

    public static void main(String[] args) {
        JTableRowDelDemo rowDelDemo = new JTableRowDelDemo();
        rowDelDemo.setVisible(true);
    }

    public JTableRowDelDemo(){
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowActivated(WindowEvent e) {
                do_this_windowActivated(e);
            }
        });
        setTitle("图书信息表");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(500,500,400,300);
        jPanel = new JPanel();
        jPanel.setBorder(new EmptyBorder(5,5,5,5));
        jPanel.setLayout(new BorderLayout(0,0));
        setContentPane(jPanel);
        JPanel panel = new JPanel();
        jPanel.add(panel, BorderLayout.SOUTH);
        JButton button = new JButton("删除");
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                do_button_actionPerformed(e);
            }
        });
        panel.add(button);
        JScrollPane scrollPane = new JScrollPane();
        jPanel.add(scrollPane, BorderLayout.CENTER);
        jTable = new JTable();
        jTable.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        scrollPane.setViewportView(jTable);

    }

    protected void do_this_windowActivated(WindowEvent e){
        DefaultTableModel tableModel = (DefaultTableModel)jTable.getModel();
        tableModel.setRowCount(0);
        tableModel.setColumnIdentifiers(new Object[]{"书名","出版社","出版时间","丛书类别","定价"});
        tableModel.addRow(new Object[]{"Java从入门到精通（第2版）","清华大学出版社","2010-07-01","软件工程师入门丛书","59.8元"});    //增加列
        tableModel.addRow(new Object[]{"PHP从入门到精通（第2版）","清华大学出版社","2010-07-01","软件工程师入门丛书","69.8元"});
        tableModel.addRow(new Object[]{"Visual Basic从入门到精通（第2版）","清华大学出版社","2010-07-01","软件工程师入门丛书","69.8元"});
        tableModel.addRow(new Object[]{"Visual C++从入门到精通（第2版）","清华大学出版社","2010-07-01","软件工程师入门丛书","69.8元" });
        jTable.setRowHeight(30);
        jTable.setModel(tableModel);
    }

    protected  void do_button_actionPerformed(ActionEvent e){
        DefaultTableModel tableModel = (DefaultTableModel) jTable.getModel();
        int[] selectedRows = jTable.getSelectedRows();
        for (int i = 0; i < selectedRows.length; i++) {
            tableModel.removeRow(selectedRows[0]);
        }
        jTable.setModel(tableModel);
    }

}
